package org.whale.springcloud.eureka.user.ribbon.service.impl;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.whale.springcloud.eureka.common.entity.JsonResponse;
import org.whale.springcloud.eureka.user.ribbon.config.UserRibbonConfig;
import org.whale.springcloud.eureka.user.ribbon.service.UserRibbonService;

import java.util.Map;

@Service
public class UserRibbonServiceImpl implements UserRibbonService {

  private static final Logger logger = LoggerFactory.getLogger(UserRibbonServiceImpl.class);

  @Autowired private RestTemplate restTemplate;

  @Autowired private UserRibbonConfig userRibbonConfig;

  @HystrixCommand(fallbackMethod = "errorBack") // 熔断
  public JsonResponse<String> queryUserInfo(Map<String, String> params) {

    // 注册服务之后 可以通过服务名称进行访问
    String url = "http://" + userRibbonConfig.getServerAppName() + "/userServer/queryUserInfo";
    params.put("clientName", "ribbon");
    logger.info("start query user info : ");
    logger.info("query user info params : " + params.toString());
    logger.info("query user info url : " + url);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("clientName", params.get("clientName"));
    HttpEntity<LinkedMultiValueMap<String, String>> requestEntity =
        new HttpEntity<LinkedMultiValueMap<String, String>>(map);
    ParameterizedTypeReference<JsonResponse<String>> typeRef =
        new ParameterizedTypeReference<JsonResponse<String>>() {};
    //    // 参数丢失
    // TODO LWL
    //    JsonResponse<String> result =
    //        restTemplate.exchange(url, HttpMethod.POST, requestEntity, typeRef).getBody();
    JsonResponse<String> result = restTemplate.postForObject(url, map, JsonResponse.class);
    logger.info("query user info result : " + result.getMessage());

    return result;
  }

  private JsonResponse<String> errorBack(Map<String, String> params) {
    logger.info("fall back error*******");
    logger.info("params:" + params.toString());
    return JsonResponse.fail("error back", "error back result");
  }
}
